package com.runfast.paotui.dao.type;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author: lijin
 * @date: 2018年03月19日
 */
@MappedTypes(List.class)
public class ListToStringTypeHandler extends BaseTypeHandler<List<String>> {
    public static final String[] separator = {",","，"};


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        String value = null;
        if (parameter != null) {
            List list = (List) parameter;
            StringBuffer stringBuffer = new StringBuffer();
            for (Object o : list) {
                if(StringUtils.isBlank(o.toString()))continue;
                stringBuffer.append(o != null ? o.toString() : "");
                stringBuffer.append(separator[0]);
            }
            value = stringBuffer.substring(0,stringBuffer.length());
        }
        ps.setString(i, value);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String rsString = rs.getString(columnName);
        return toList(rsString);
    }

    private List<String> toList(String parameter) {
        List<String> result = new ArrayList<>();
        if (StringUtils.isNotBlank(parameter)) {
            String[] split = parameter.split("["+separator[0]+","+separator[1]+"]", -1);
            for (String s : split) {
                if(StringUtils.isNotBlank(s))result.add(s);
            }
        }
        return result;
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String rsString = rs.getString(columnIndex);
        return toList(rsString);
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String rsString = cs.getString(columnIndex);
        return toList(rsString);
    }
}
